#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIOT智能学习桌项目 - 主启动脚本
"""

import sys
import os
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))

from config import ensure_directories, SYSTEM_CONFIG
from utils.logger import logger
from utils.exceptions import SmartDeskException

def check_dependencies():
    """检查项目依赖"""
    required_packages = [
        'opencv-python',
        'mediapipe', 
        'numpy',
        'SpeechRecognition',
        'pyttsx3'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'opencv-python':
                import cv2
            elif package == 'SpeechRecognition':
                import speech_recognition
            else:
                __import__(package.lower().replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        logger.error(f"缺少依赖包: {', '.join(missing_packages)}")
        logger.info("请运行: pip install -r requirements.txt")
        return False
    
    logger.info("依赖检查通过")
    return True

def run_simulator():
    """运行仿真程序"""
    try:
        from 仿真测试.simulator_python import SmartDeskSimulator
        simulator = SmartDeskSimulator()
        simulator.start_system()
        
        import time
        while True:
            time.sleep(5.0)
            simulator.display_status()
            
    except KeyboardInterrupt:
        logger.info("用户中断程序")
        simulator.stop_system()
    except Exception as e:
        logger.error(f"仿真程序运行错误: {e}")

def run_voice_system():
    """运行语音识别系统"""
    try:
        from 智能学习桌_语音版 import SmartDeskWithVoice
        desk = SmartDeskWithVoice()
        desk.run()
    except Exception as e:
        logger.error(f"语音系统运行错误: {e}")

def run_posture_detection():
    """运行坐姿检测"""
    try:
        from 摄像头坐姿检测模块.main import PostureDetectionApp
        app = PostureDetectionApp()
        app.run()
    except Exception as e:
        logger.error(f"坐姿检测运行错误: {e}")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='AIOT智能学习桌项目启动器')
    parser.add_argument('--mode', choices=['simulator', 'voice', 'posture', 'menu'], 
                       default='menu', help='运行模式')
    parser.add_argument('--debug', action='store_true', help='启用调试模式')
    parser.add_argument('--check-deps', action='store_true', help='仅检查依赖')
    
    args = parser.parse_args()
    
    # 设置调试模式
    if args.debug:
        SYSTEM_CONFIG['debug_mode'] = True
        SYSTEM_CONFIG['log_level'] = 'DEBUG'
    
    # 确保目录存在
    ensure_directories()
    
    logger.info("AIOT智能学习桌项目启动")
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    if args.check_deps:
        logger.info("依赖检查完成")
        return
    
    try:
        if args.mode == 'simulator':
            logger.info("启动仿真模式")
            run_simulator()
        elif args.mode == 'voice':
            logger.info("启动语音识别模式")
            run_voice_system()
        elif args.mode == 'posture':
            logger.info("启动坐姿检测模式")
            run_posture_detection()
        else:
            logger.info("启动菜单模式")
            from 启动菜单 import main as menu_main
            menu_main()
            
    except SmartDeskException as e:
        logger.error(f"智能学习桌错误: {e}")
        sys.exit(1)
    except Exception as e:
        logger.error(f"未知错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()